package com.cipe.cmrs.controllers;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.cipe.cmrs.bean.CipeprojectBean;
import com.cipe.cmrs.bean.ProjectReportBean;
import com.cipe.cmrs.model.Cipeproject;
import com.cipe.cmrs.model.Projectreport;
import com.cipe.cmrs.service.CipeprojectService;
import com.cipe.cmrs.service.ProjectReportService;
import com.cipe.cmrs.util.Constants;

/**
 * 
 * @author krishna (kanhu.aum@gmail.com)
 *
 */
@Controller
public class ProjectReportController extends BaseController{
	private static final long serialVersionUID = -2482539586632027078L;
	
	// static variables related to progress reports
	private static final int MAX_REPORTINGS_DEFAULT_NUMBER = 9;
	public static final String REDIRECT_TO_REPORT_LIST_PAGE = "redirect:showAddReportingrequirements.do?cipeprojectId=";
	private static final String SHOW_REPORT_LIST_URL = "/secure/saveProjectReportLines.do";
	
	@Autowired
	ProjectReportService projectReportService;
	@Autowired
	private CipeprojectService cipeprojectService;
	
	@RequestMapping("/secure/findResultProjectReportWithProcedure.do")
	public String findResultProjectReportWithProcedure(@ModelAttribute("report") Projectreport projectreport, Model model) {
	model.addAttribute("reportList", projectReportService.findallProjectReport(projectreport.getPrc()));
	model.addAttribute("message", projectreport.getMessage());
	return "findProjectreport";
	}

	
    @RequestMapping(value = "/secure/showAddReportingrequirements.do", method = RequestMethod.GET)
	public String showAddReportingrequirements(@RequestParam Integer cipeprojectId, @RequestParam(value="narEdit", required=false) Boolean narrativeSectionEditable,
				@RequestParam(value="finEdit", required=false) Boolean financialSectionEditable, Model model) {

		ProjectReportBean projectReportBean = new ProjectReportBean(cipeprojectId);		
		
		// load the existing lines for the current project id
		List<Projectreport> projectReports = projectReportService.findProjectReportsByProjectId(cipeprojectId);
		if(projectReports != null && !projectReports.isEmpty()) {
			for(Projectreport report : projectReports) {
				if(Constants.NARRATIVE_TYPE.equals(report.getType())) {
					projectReportBean.addNarrativeReport(report);
				} else if(Constants.FINANCIAL_TYPE.equals(report.getType())) {
					projectReportBean.addFinancialReport(report);
				}
			}
		}
		
		// complete the reporting lines up to the MAX_REPORTINGS_DEFAULT_NUMBER number (if needed; normally for a new process) 
		if(projectReportBean.getNarrativeReports().size() < 9) {
			for(int i=projectReportBean.getNarrativeReports().size() + 1;i<=MAX_REPORTINGS_DEFAULT_NUMBER;i++) {
				projectReportBean.addNarrativeReport(new Projectreport(Constants.NARRATIVE_TYPE));
			}
		}
		
		// complete the reporting lines up to the MAX_REPORTINGS_DEFAULT_NUMBER number (if needed; normally for a new process) 
		if(projectReportBean.getFinancialReports().size() < 9) {
			for(int i=projectReportBean.getFinancialReports().size() + 1;i<=MAX_REPORTINGS_DEFAULT_NUMBER;i++) {
				projectReportBean.addFinancialReport(new Projectreport(Constants.FINANCIAL_TYPE));
			}
		}
		
		projectReportBean.setNarrativeSectionEditable((narrativeSectionEditable != null && narrativeSectionEditable == true) ? true : false);
		projectReportBean.setFinancialSectionEditable((financialSectionEditable != null && financialSectionEditable == true) ? true : false);

		model.addAttribute("projectReportBean", projectReportBean);
		
		Cipeproject cipeproject = cipeprojectService.findById(cipeprojectId);
		model.addAttribute("cipeproject", cipeproject);
		
		return "editReportingrequirements";
	}	
	
	
	@RequestMapping(value=SHOW_REPORT_LIST_URL, method=RequestMethod.POST)
	public String saveNarrativeAndFinancialReportLines(@ModelAttribute("projectReportBean") ProjectReportBean projectReportBean, 
			BindingResult result, Model model, HttpServletRequest request) {

		if (!result.hasErrors()) {
			projectReportService.persistProjectReportData(projectReportBean);
			saveMessage(request, getText("editReportingrequirements.save.success"));
		}
		
		return constructGotoListURL(REDIRECT_TO_REPORT_LIST_PAGE + projectReportBean.getCipeprojectId() + 
				(!result.hasErrors()?"&reportsAreSaved=true":""), 
					projectReportBean);
	}
	
	@RequestMapping(value=SHOW_REPORT_LIST_URL, params="delRowNar", method=RequestMethod.POST)
	public String deleteNarrativeSelectedRows(@ModelAttribute("projectReportBean") ProjectReportBean projectReportBean, 
			@RequestParam Integer[] selNar, BindingResult result, Model model, HttpServletRequest request) {
		
		deleteSelectedRows(selNar);
		saveMessage(request, getText("editReportingrequirements.delete.success"));
	
		return constructGotoListURL(REDIRECT_TO_REPORT_LIST_PAGE + projectReportBean.getCipeprojectId(), projectReportBean);
	}
	
	@RequestMapping(value=SHOW_REPORT_LIST_URL, params="delRowFin", method=RequestMethod.POST)
	public String deleteFinancialSelectedRows(@ModelAttribute("projectReportBean") ProjectReportBean projectReportBean, 
			@RequestParam Integer[] selFin, BindingResult result, Model model, HttpServletRequest request) {
		
		deleteSelectedRows(selFin);
		saveMessage(request, getText("editReportingrequirements.delete.success"));
		
		return constructGotoListURL(REDIRECT_TO_REPORT_LIST_PAGE + projectReportBean.getCipeprojectId(), projectReportBean);
	}	
	
	private void deleteSelectedRows(Integer[] reportIds) {
		if(reportIds != null) {
			for(Integer reportId: reportIds) {
				projectReportService.deleteReportLineById(reportId);
			}
		}
	}
	
	@RequestMapping(value=SHOW_REPORT_LIST_URL, params="addRowNar", method=RequestMethod.POST)
	public String addNarrativeProgressReportRow(@ModelAttribute("projectReportBean") ProjectReportBean projectReportBean, 
			BindingResult result, Model model, HttpServletRequest request) {

		projectReportBean.addNarrativeReport(new Projectreport(Constants.NARRATIVE_TYPE));
		projectReportService.persistProjectReportData(projectReportBean);
		
		return constructGotoListURL(REDIRECT_TO_REPORT_LIST_PAGE + projectReportBean.getCipeprojectId(), projectReportBean);
	}
	
	@RequestMapping(value=SHOW_REPORT_LIST_URL, params="addRowFin", method=RequestMethod.POST)
	public String addFinancialProgressReportRow(@ModelAttribute("projectReportBean") ProjectReportBean projectReportBean, 
			BindingResult result, Model model, HttpServletRequest request) {

		projectReportBean.addFinancialReport(new Projectreport(Constants.FINANCIAL_TYPE));
		projectReportService.persistProjectReportData(projectReportBean);
		
		return constructGotoListURL(REDIRECT_TO_REPORT_LIST_PAGE + projectReportBean.getCipeprojectId(), projectReportBean);
	}	
	
	private String constructGotoListURL(String mainUrl, ProjectReportBean projectReportBean) {
		return mainUrl + 
				(projectReportBean.isNarrativeSectionEditable()?"&narEdit=true":"") + 
				(projectReportBean.isFinancialSectionEditable()?"&finEdit=true":"");
	}
}
